package com.wiken.addressservice.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wiken.addressservice.entity.Address;
import com.wiken.addressservice.service.impl.AddressServiceImpl;
import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.R;
import com.wiken.servicecommon.common.exception.DefaultException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wiken
 * @since 2022-12-28
 */
@RestController
@RequestMapping("/addressservice/address")
@Api("address-api")
public class AddressController {

    @Autowired
    private AddressServiceImpl addressService;

    @PostMapping("/addAddress")
    public R addAddress(@RequestBody Address address, @RequestHeader("Authorization") String token){
        boolean ok = addressService.addAddress(address, token);

        if(!ok) throw new DefaultException(Code.ERROR, "添加地址失败");

        return R.ok().code(Code.SUCCESS).message("添加地址成功");
    }

    @PutMapping("/updateAddress")
    public R updateAddress(@RequestBody Address address, @RequestHeader("Authorization") String token){
        boolean ok = addressService.updateAddress(address, token);

        if(!ok) throw new DefaultException(Code.ERROR, "修改地址失败");

        return R.ok().code(Code.SUCCESS).message("地址修改成功").data("data", address);
    }

    @DeleteMapping("/deleteAddress")
    public R deleteAddress(@RequestBody Address address, @RequestHeader("Authorization") String token){
        boolean ok = addressService.delAddress(address, token);

        if(!ok) throw new DefaultException(Code.ERROR, "删除地址失败");

        return R.ok().code(Code.SUCCESS).message("地址删除成功");
    }

    @PostMapping("/getAddress")
    public R getAddress(@RequestBody Page page, @RequestHeader("Authorization") String token){

        Page addressPage = addressService.getAddressAll(page, null, token);

        return R.ok().code(Code.SUCCESS).message("获取成功").data("addressList", addressPage);
    }

    @GetMapping("/getCode")
    public R getCode(@RequestParam ("region") String region){
        RestTemplate restTemplate = new RestTemplate();

        String url = "https://api.map.baidu.com/api_region_search/v1/?keyword="+region+"&sub_admin=1&ak=xd5eRz3Gxg3EXodl6NSsn9NSYm3CU9tp&extensions_code=1";

        String data = restTemplate.getForObject(url, String.class);

        return R.ok().code(Code.SUCCESS).message("获取成功").data("data", data);
    }
}
